package com.example.canavar;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.utils.SearchResult;
import com.example.utils.SearchResultManager;
import com.example.utils.SearchResultUpdateListener;
import com.example.utils.SearchTaskDelegate;
import com.example.utils.Utils;

public class MainActivity extends Activity implements
		SearchResultUpdateListener, SearchTaskDelegate {

	// Animations
	AnimationDrawable bkgroundAnim, jumpingCartAnim;

	TextView mTvStatus;
	TextView mTvSearch;
	ImageView mCart;
	public static String K_NONE;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mTvStatus = (TextView) findViewById(R.id.tv_status);
		mTvSearch = (TextView) findViewById(R.id.tv_btn);
		mCart = (ImageView) findViewById(R.id.cart);
		K_NONE = getResources().getString(R.string.no_value);
		jumpingCartAnim = (AnimationDrawable) mCart.getDrawable();

		getFragmentManager().beginTransaction()
				.add(R.id.layout_top, new SettingsFragment()).commit();

		PreferenceManager.setDefaultValues(MainActivity.this,
				R.xml.pref_general, false);

		updateBigButton();

		// Set this fragment as the listener for search result updates.
		SearchResultManager.getInstance().setSearchResultUpdateListener(this);
	}

	public void showLog() {
		if (SearchTask.isRunning)
			return;

		Intent intent = new Intent(this, DisplayLogActivity.class);
		// String logs =
		// intent.putExtra(EXTRA_MESSAGE, message);
		startActivity(intent);
	}

	public void goClick(View view) {

		// Already running, skip
		if (SearchTask.isRunning) {
			Utils.Log("SearchTask is busy, ignored.");
			return;
		}

		SearchTask search = new SearchTask(getApplicationContext());
		search.setDelegate(this);
		search.execute();
	}

	private void updateBigButton() {

		// black button with animation
		if (SearchTask.isRunning) {
			startSearchAnimations();
		} else {
			stopSearchAnimations();
		}

	}

	// start with yellow button
	private void startSearchAnimations() {

		LinearLayout mButton = (LinearLayout) findViewById(R.id.big_button);

		// Step1: button turns dark
		bkgroundAnim = (AnimationDrawable) mButton.getBackground();
		bkgroundAnim.start();

		// Step2 : cart leaves towards right

		Animation slideAnim = AnimationUtils.loadAnimation(this,
				R.animator.cart_anim);
		slideAnim.setFillAfter(false);
		mCart.startAnimation(slideAnim);

		// Step3: things start flying
		LinearLayout mFlyingLayout = (LinearLayout) findViewById(R.id.flying_images_container);
		mFlyingLayout.setVisibility(View.VISIBLE);

		for (int i = 0; i < ((ViewGroup) mFlyingLayout).getChildCount(); ++i) {
			View flyingItem = ((ViewGroup) mFlyingLayout).getChildAt(i);
			Animation flyAnim = AnimationUtils.loadAnimation(this,
					R.animator.fly_anim);
			flyAnim.setDuration(new Random().nextInt(3000) + 1000);
			flyAnim.setStartOffset(new Random().nextInt(1000));
			flyingItem.startAnimation(flyAnim);
		}

		// Step5: Search texts appear
		mTvSearch.setText(getString(R.string.searching));

		// Step5: cart is jumping changing

		jumpingCartAnim.start();

		// // Step1 : create the RotateAnimation object
		// RotateAnimation anim = new RotateAnimation(0f, 350f, 15f, 15f);
		// // Step 2: Set the Animation properties
		// anim.setInterpolator(new LinearInterpolator());
		// anim.setRepeatCount(Animation.INFINITE);
		// anim.setDuration(700);
		//
		// mStatus.startAnimation(anim);

	}

	private void stopSearchAnimations() {

		LinearLayout mFlyingLayout = (LinearLayout) findViewById(R.id.flying_images_container);
		mFlyingLayout.setVisibility(View.GONE);

		if (bkgroundAnim != null) {
			bkgroundAnim.stop();
			bkgroundAnim.selectDrawable(0);
		}

		if (jumpingCartAnim != null) {
			jumpingCartAnim.stop();
			jumpingCartAnim.selectDrawable(0);
		}

		mTvSearch.setText(getString(R.string.app_name));
		mTvStatus.setText(R.string.go_search);
							
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		SearchResultManager.getInstance().init(this);

		updateService(this, TimerService.RQS_NO_CHANGE);
	}

	public static void updateService(Context context, int change) {

		String freqValue = PreferenceManager.getDefaultSharedPreferences(
				context).getString(SettingsFragment.FREQS_PREF_KEY, "");

		Utils.Log("freqValue value " + freqValue);

		if (freqValue.isEmpty() || freqValue.equalsIgnoreCase("0"))
			change = TimerService.RQS_STOP_SERVICE;

		Intent intent = new Intent(context, TimerService.class);
		intent.setAction(TimerService.ACTION);

		switch (change) {
		case TimerService.RQS_STOP_SERVICE:
			intent.putExtra(TimerService.RQS, TimerService.RQS_STOP_SERVICE);
			context.sendBroadcast(intent);
			break;
		case TimerService.RQS_FREQ_CHANGE:
			intent.putExtra(TimerService.RQS, TimerService.RQS_FREQ_CHANGE);
			intent.putExtra(TimerService.INTERVAL, freqValue);
			context.sendBroadcast(intent);
		default:
			if (!TimerService.IsServiceRunning(context)) {
				intent.putExtra(TimerService.INTERVAL, freqValue);
				context.startService(intent);
			}
			break;
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		Utils.Log("onPause called");
		SearchResultManager.getInstance().saveState(this);
	}

	@Override
	public void onSearchResultsChanged(final SearchResult res) {
		// addItem
		Utils.Log("SearchResultsChanged fired.");

		getFragmentManager()
				.beginTransaction()
				.replace(R.id.carousel_fragment_container,
						new CarouselFragment()).commit();

		// final CarouselFragment carousel = (CarouselFragment)
		// getFragmentManager()
		// .findFragmentById(R.id.carousel_fragment_container);
		// if (carousel != null) {
		// runOnUiThread(new Runnable() {
		// @Override
		// public void run() {
		// Utils.Log("addNewBox run.");
		// carousel.addNewBox(res);
		// }
		// });
		// } else {
		// getFragmentManager()
		// .beginTransaction()
		// .replace(R.id.carousel_fragment_container,
		// new CarouselFragment()).commit();
		// }
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		SearchResultManager.getInstance()
				.removeSearchResultUpdateListener(this);
	}

	@Override
	public void onTaskStarted(String params) {
		updateBigButton();
	}

	@Override
	public void onTaskCompleted(String completed) {
		updateBigButton();
	}

	@Override
	public void onTaskUpdate(String log) {
		// update button text
		Utils.Log("onSearchLogChanged: " + log);
		mTvStatus.setText(log);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.activity_main, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.action_log:
	            showLog();
	            return true;	        
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	

	static boolean active = false;

	@Override
	public void onStart() {
		super.onStart();
		active = true;
	}

	@Override
	public void onStop() {
		super.onStop();
		active = false;
	}
}
